package nju.eai.seller.util;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;



import nju.eai.seller.beans.ProductBean;

public class ProductMngr {
	private Connection con;
	private Statement statement;

	public ProductMngr() throws ClassNotFoundException, SQLException {
		this.con = DBConMngr.createConnection();
		this.statement = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
				ResultSet.CONCUR_READ_ONLY);
	}



	public ProductBean[] getAllProducts() throws SQLException {
		int count = 0;

		String query = "SELECT * FROM product;";
		ResultSet rs = statement.executeQuery(query);
		rs.last();
		count = rs.getRow();
		rs.beforeFirst();

		ProductBean[] products = new ProductBean[count];
		int i = 0;
		while (rs.next()) {
			products[i] = new ProductBean();
			
			products[i].setPid(rs.getString(1));
			products[i].setName(rs.getString(2));
			products[i].setType1(rs.getString(3));
			products[i].setType2(rs.getString(4));
			products[i].setPrice(rs.getDouble(5));
			
			++i;
		}

		return products;
	};
	
	
	
	public ProductBean[] getProductsByType(String type) throws SQLException {
		int count = 0;

		String query = "SELECT * FROM product WHERE type1 =\'"+type+"\'  OR type2 = \'" +type+"\';";
		System.out.println(query);
		ResultSet rs = statement.executeQuery(query);
		rs.last();
		count = rs.getRow();
		rs.beforeFirst();

		ProductBean[] products = new ProductBean[count];
		int i = 0;
		while (rs.next()) {
			products[i] = new ProductBean();
			
			products[i].setPid(rs.getString(1));
			products[i].setName(rs.getString(2));
			products[i].setType1(rs.getString(3));
			products[i].setType2(rs.getString(4));
			products[i].setPrice(rs.getDouble(5));
			
			++i;
		}

		return products;
	};
	
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}
